package com.lanou3g.ptp.remind.entity;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lanou3g.ptp.achievement.service.DiaryService;
import com.lanou3g.ptp.entity.SignInDate;
import com.lanou3g.ptp.signInDate.service.SignInDateService;
import com.lanou3g.ptp.taskstudent.service.TaskStudentService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class DiaryJob implements Job {

    private Long parameter;

    public DiaryJob() {
    }

    public void setParameter(Long parameter) {
        this.parameter = parameter;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Reference
    private SignInDateService signInDateService;

    @Reference
    private TaskStudentService taskStudentService;

    @Reference
    private DiaryService diaryService;

    @Value("REMIND-DIARY-")
    private String REDIS_DIARYREMIND_KEY_PREFIX;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

        System.out.println("ID为 " + parameter + " 的实习任务开始了！！！！定时提醒日志…………………………");

        List<SignInDate> signTime = signInDateService.findSignTime(parameter);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String nowDate = simpleDateFormat.format(new Date());

        boolean isToday = false;


        for (SignInDate signInDate : signTime) {
            if (simpleDateFormat.format(signInDate.getDate()).equals(nowDate)){
                isToday = true;
                break;
            }
        }

        System.out.println(isToday);

        if (isToday){
            ArrayList<Long> students = taskStudentService.findByTaskId(parameter);

            for (Long student : students) {
                if (diaryService.findByTime(new Date(),parameter,student) == null){

                    String key = REDIS_DIARYREMIND_KEY_PREFIX + parameter;

                    redisTemplate.opsForHash().put(key,student.toString(),nowDate);

                }

            }
        }


    }



}
